<template>
  <div class="defectPendingDetails h100">
    <editPageNew
      ref="editPage"
      :rightBtnArr="rightBtnArr"
      :stepConfig="stepConfig"
      :moreBtnArr="moreBtnArr"
      showStep
      showTopTitle
      :showMore="showMore"
      :creatInfo="formData"
    >
      <template slot="editPageTitle">
        <i class="el-icon-document TitleImg"></i>
        缺陷待处理单 {{ formData.code }}
      </template>
      <div class="orderTitle" :class="{ redLine: !orderTitle }">
        <div class="tipText">标题自动生成规则：{关联工单的标题}_缺陷待处理</div>
        <div v-show="!showInput" class="name">
          <span style="color: red"></span>
          <span class="titleText" :title="orderTitle">{{ orderTitle }}</span>
          <el-link
            v-show="!baseAttachBtn && !disabled"
            style="font-size: 20px"
            icon="el-icon-edit-outline"
            @click="editTitle"
          ></el-link>
        </div>
        <div v-show="showInput" class="name-input">
          <el-input
            type="text"
            v-model="orderTitle"
            @blur="loseFocus"
            @change="userInputTitle"
            placeholder="请输入名称"
            clearable
            ref="mark"
          >
            <template slot="prepend">标题</template>
          </el-input>
        </div>

        <!-- <div class="tipText">标题规则：关联工单的标题_缺陷待处理</div>
        <el-input v-model="orderTitle" placeholder="请输入工单标题" :disabled="baseAttachBtn"></el-input>-->
      </div>
      <el-collapse v-model="activeNames">
        <el-collapse-item name="1">
          <template slot="title">基本信息</template>
          <editForm
            :formConfig="editFormConfig"
            ref="basicForm"
            :formData="formData"
          >
            <template #defectCode="{ editFormInfo }">
              <el-input
                size="mini"
                readonly
                :disabled="disabled"
              >
                <span
                  slot="prefix"
                  class="orderCode"
                  @click="showOrder()"
                  >{{ editFormInfo.defectCode }}</span
                >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  :disabled="disabled"
                  @click.stop="showDefectOrder('selectOrder')"
                ></el-button>
              </el-input>
            </template>
          </editForm>
        </el-collapse-item>
        <div v-if="showWorkFlow">
          <el-collapse-item name="2">
            <template slot="title">审批信息</template>
            <workFlow
              ref="workFlow"
              v-if="showWorkFlow"
              :isDetails="pageType == 'query'"
              :currentFlowData="formData"
              @submitSuccess="workFlowSuccess"
              workflowCode="defect_pending"
            ></workFlow>
          </el-collapse-item>
        </div>
      </el-collapse>
    </editPageNew>
    <dialogPublic
      :title="'审核信息'"
      :show.sync="showFlowDialog"
      noFootBtn
      appendTobody
      fullscreen
      @doClose="() => (showFlowDialog = false)"
    >
      <workFlow
        v-if="showFlowDialog"
        :isDetails="pageType == 'query'"
        :currentFlowData="formData"
        @submitSuccess="workFlowInitSuccess"
        workflowCode="defect_pending"
      ></workFlow>
    </dialogPublic>
    <dialogPublic
      :title="'选择关联工单'"
      :show.sync="showWorkOrder"
      @doSubmit="selectOrders"
      @doClose="showDefectOrder('closeOrder')"
      appendTobody
      fullscreen
    >
      <workorder ref="defectOrders"></workorder>
    </dialogPublic>
  </div>
</template>

<script>
import workorder from "@/views/orderManagement/defectPending/orderList"; //缺陷工单选择
import {
  insertOrUpdate, //保存
  getDetails, // 查询
  deleteById, // 删除
  insert,
} from "@/api/orderManagement/defectPending";
import {
  getOrderDictionApi, //权限
} from "@/api/orderManagement/common";
import { getDetailsApi } from "@/api/orderManagement/defectOrder";
export default {
  components: {
    workorder,
  },
  data() {
    return {
      pageName: "缺陷待处理单",
      userInfo: this.$store.getters.userInfo,
      formData: {},
      status: "",
      projectName: "",
      showMore: false,
      userInput: false,
      showInput: false,
      disabled: false,
      showWorkOrder: false,
      showFlowDialog: false,
      orderTitle: "",
      defectQueryData: {},
      activeNames: ["1"],
      btnJurisdiction: [],
      orderStatus: ["DRAFT", "WAIT_REVIEW", "REVIEWED"],
      editFormConfig: {
        itemArr: [
          {
            type: "text",
            label: "缺陷工单:",
            prop: "defectCode",
            idStr: "defectId",
            placeholder: "请选择工单",
            required: true,
            span: 8,
          },
          {
            type: "datetime",
            label: "预计处理时间",
            prop: "expectProcessTime",
            required: true,
            methods: (obj) => {},
            span: 8,
          },
          {
            type: "textarea",
            label: "申请原因",
            prop: "reason",
            required: true,
            methods: (obj) => {},
            span: 24,
            rows: 7,
          },
        ],
      },
    };
  },
  methods: {
    init() {
      this.formData.id = this.$route.query.id || null;
      if (this.formData.id) {
        this.pageType = "edit";
        this.getDetailsById();
      } else {
        this.pageType = this.$route.query.pageType;
        this.showInput = true;
        if (this.pageType == "orderAdd") {
          let { orderId, orderStatus, orderCode } = this.$route.query;
          this.defectQueryData.id = orderId;
          this.defectQueryData.status = orderStatus;
          this.formData.defectCode = orderCode;
          this.formData.defectId = orderId;
          // 自动生成标题
          getDetailsApi(orderId).then((res) => {
            this.projectName = res.data.title;
          });
        }
      }
      // let haveJurisdiction = this.$store.getters["isBtnAuth"]("edit");
      // if (!haveJurisdiction) {
      //   this.disabled = true;
      //   this.editFormConfig.itemArr.map(i => (i.disabled = true));
      // }
    },
    //获取页面权限
    jurisdiction() {
      let form = {
        orderId: this.formData.id,
        orderStatus: this.status,
        orderType: "defectPending",
      };
      getOrderDictionApi(form).then((res) => {
        let data = res.data;
        if (Array.isArray(data)) {
          this.btnJurisdiction = data;
        } else {
          this.btnJurisdiction = [];
        }
        this.changePageType();
      });
    },
    changePageType() {
      let status = this.status || "";
      //用户角色权限
      let userJurisdiction = this.$store.getters["isBtnAuth"]("edit");
      //业务控制权限
      let businessJurisdiction = this.$utils.getJurisdiction(
        this.btnJurisdiction,
        "save"
      );
      let haveJurisdiction = userJurisdiction && businessJurisdiction;
      //确定pageType类型
      if (haveJurisdiction && status == "DRAFT") {
        this.editFormConfig.itemArr.map((item) => {
          item.disabled = false;
        });
      } else {
        this.editFormConfig.itemArr.map((item) => {
          item.disabled = true;
        });
      }
    },
    showDefectOrder(type) {
      if (type === "selectOrder") {
        this.showWorkOrder = true;
      } else {
        this.showWorkOrder = false;
      }
    },
    // 选择缺陷工单
    selectOrders() {
      this.showWorkOrder = false;
      let data = this.$refs.defectOrders.getSelectData();
      let { id, status, code, title } = data;
      this.$refs.basicForm.setFormItem("defectCode", code);
      this.$refs.basicForm.setFormItem("defectId", id);
      this.projectName = title;
      this.defectQueryData.id = id;
      this.defectQueryData.status = status;
    },
    async doSubmit(type) {
      let data = {};
      //基本信息的保存
      if (this.orderTitle == "") {
        this.$message.warning("请填写标题!");
      } else {
        data = await this.$refs.basicForm.getFormData();
        data.title = this.orderTitle;
        delete data.defectCode;
        if (type == "submit") {
          this.$confirm(`提交后数据将会自动保存，是否继续`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.submitOrder(data, type);
            })
            .catch((e) => {});
        } else {
          this.submitOrder(data, type);
        }
      }
    },
    submitOrder(data, type) {
      let status = this.status;
      insertOrUpdate(data).then((res) => {
        this.$utils.updateStorage();
        this.$message.success("操作成功！");
        this.formData = res.data;
        this.status = res.data.status;
        if (this.pageType == "add") {
          this.pageType = "edit";
          this.$utils.addOperateLog(this.formData.id, `新建了${this.pageName}`);
          if (type == "submit") {
            this.showFlowDialog = true;
          } else {
            this.changeRouter();
          }
        } else if (this.pageType == "orderAdd") {
          // 缺陷工单模块过来开待处理单
          this.$utils.addOperateLog(this.formData.id, `新建了${this.pageName}`);
          this.changeRouter();
        } else if (status == "DRAFT" && type == "submit") {
          this.showFlowDialog = true;
        } else if (status == "DRAFT" && type == "save") {
          this.$utils.addOperateLog(this.formData.id, `修改了${this.pageName}`);
        }
        this.getDetailsById(res.data.id);
      });
    },
    changeRouter() {
      /* 修改路由参数 */
      let obj = JSON.parse(JSON.stringify(this.$router.currentRoute.query));
      obj = Object.assign(obj, {
        id: this.formData.id,
        pageType: "edit",
        status: this.status,
      });
      this.$router.push({
        query: obj,
      });
    },
    // 根据id查询
    getDetailsById(id) {
      id = id ? id : this.formData.id;
      getDetails({ id }).then((res) => {
        let data = res.data || {};
        this.orderTitle = data.title;
        this.status = data.status;
        let { defectId } = data;
        this.jurisdiction();
        getDetailsApi(defectId).then((res) => {
          if (this.$refs.basicForm) {
            this.$refs.basicForm.setFormItem("defectCode", res.data.code);
            this.$refs.basicForm.setFormItem("defectId", res.data.id);
          }
          this.defectQueryData.id = res.data.id;
          this.defectQueryData.status = res.data.status;
        });
        this.formData = data;
      });
    },
    // 删除
    deleteData() {
      this.$confirm(`是否确认删除`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteById({ id: this.formData.id }).then((res) => {
            this.$utils.updateStorage();
            this.$message.success("操作成功");
            this.$refs.editPage.closePage(1000);
          });
        })
        .catch((e) => {});
    },
    workFlowSuccess() {
      this.$utils.updateStorage();
      if (this.$refs.workFlow) {
        this.$utils.addOperateLog(this.formData.id, `审批了${this.pageName}`);
        this.$refs.workFlow.getFlowInfo();
      }
      this.getDetailsById();
      setTimeout(() => {
        this.changeRouter();
      }, 500);
    },
    // 保存提交
    workFlowInitSuccess() {
      this.showFlowDialog = false;
      this.$utils.updateStorage();
      this.$utils.addOperateLog(this.formData.id, `提交了${this.pageName}`);
      if (this.$refs.workFlow) {
        this.$refs.workFlow.getFlowInfo();
      }
      this.getDetailsById();
      setTimeout(() => {
        this.changeRouter();
      }, 500);
    },
    //显示缺陷工单详情
    async showOrder() {
      if (this.defectQueryData.id) {
        let form = {
          pageType: "ditails",
          id: this.defectQueryData.id,
          status: this.defectQueryData.status,
        };
        let { href } = this.$router.resolve({
          path: "/orderManagement/defectOrder/details",
          query: form,
        });
        window.open(href, "_blank");
      }
    },
    //用户输入工单标题
    userInputTitle(val) {
      if (["", null].includes(val) || val.match(/^[ ]*$/)) {
        this.userInput = false;
      } else {
        this.userInput = true;
      }
    },
    loseFocus() {
      if (
        ["", null].includes(this.orderTitle) ||
        this.orderTitle.match(/^[ ]*$/)
      ) {
        if (this.projectName) {
          this.$message.warning("标题不能为空，已为您自动生成标题！");
          this.orderTitle = this.projectName + "_缺陷待处理";
          this.showInput = false;
        } else {
          this.showInput = true;
        }
      } else {
        this.showInput = false;
      }
    },
    //编辑标题
    editTitle() {
      this.showInput = true;
      setTimeout(() => {
        this.$refs.mark.focus();
      }, 0);
    },
  },
  created() {
    this.init();
  },
  computed: {
    // 流程配置进度
    stepConfig() {
      let step = this.orderStatus.indexOf(this.status);
      let obj = {
        nowStep: parseInt(step), //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
        stepItem: ["草稿", "待审批", "已审批"],
      };
      return obj;
    },
    // 配置进度右边按钮
    rightBtnArr() {
      let arr = [
        {
          text: "提交",
          icon: "el-icon-position",
          hide:
            ["details"].includes(this.pageType) ||
            ["WAIT_REVIEW", "REVIEWED"].includes(this.status),
          methods: () => {
            this.doSubmit("submit");
          },
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "submit",
            this.$store.getters["isBtnAuth"]("edit")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("edit") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "submit")
          ),
        },
        {
          text: "保存",
          icon: "el-icon-check",
          hide:
            ["details"].includes(this.pageType) ||
            ["WAIT_REVIEW", "REVIEWED"].includes(this.status),
          methods: () => {
            this.doSubmit("save");
          },
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "save",
            this.$store.getters["isBtnAuth"]("edit")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("edit") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "save")
          ),
        },
        {
          text: "删除",
          icon: "el-icon-delete",
          hide: ["details"].includes(this.pageType) || this.status != "DRAFT",
          methods: () => {
            this.deleteData();
          },
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "delete",
            this.$store.getters["isBtnAuth"]("delete")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("delete") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "delete")
          ),
        },
      ];
      return arr;
    },
    moreBtnArr() {
      let arr = [
        {
          text: "操作记录",
          methods: () => {
            this.$refs.editPage.showOperate();
          },
        },
      ];
      return arr;
    },
    baseAttachBtn() {
      if (["DRAFT", ""].includes(this.status)) {
        return false;
      } else {
        return true;
      }
    },
    showWorkFlow() {
      return (
        ["WAIT_REVIEW", "REVIEWED"].includes(this.status) &&
        this.pageType != "add"
      );
    },
  },
  watch: {
    status: {
      handler(val) {
        if (val == "") {
          this.showMore = false;
        } else {
          this.showMore = true;
        }
        switch (val) {
          case "DRAFT":
            this.activeNames = ["1"];
            break;
          case "WAIT_REVIEW":
            this.activeNames = ["2"];
            break;
          case "REVIEWED":
            this.activeNames = ["1", "2"];
            break;
          default:
            this.activeNames = ["1"];
            break;
        }
        if (["WAIT_REVIEW", "REVIEWED", "DEPRECATED"].includes(val)) {
          this.disabled = true;
          this.editFormConfig.itemArr.map((i) => (i.disabled = true));
        }
      },
    },
    projectName: {
      handler(val) {
        if (!this.userInput) {
          this.orderTitle = val + "_缺陷待处理";
          this.showInput = false;
        }
      },
    },
  },
};
</script>

<style lang="less" scoped>
.defectPendingDetails {
  background-color: #ffffff;
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }
  .titleText {
    display: inline-block;
    height: 30px;
    max-width: 800px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    margin-right: 5px;
  }
  .el-link {
    margin-bottom: 5px;
  }
  .tipText {
    color: #cecece;
    text-align: left;
  }

  .redLine {
    /deep/.el-input__inner {
      border: 1px solid red !important;
    }
  }
  .orderTitle {
    height: 60px;
    margin: 0 0 10px 0;
    .tipText {
      color: #cecece;
      text-align: left;
    }
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 600px;
      height: 40px;
      line-height: 40px;
    }
    .remindColor {
      /deep/.el-input__inner {
        border: 1px solid red !important;
      }
    }
  }
  .attachConten {
    display: flex;
    flex-flow: wrap nowrap;
    .redPoint {
      color: red;
    }
    .attachTitle {
      width: 135px;
      text-align: right;
      margin-right: 10px;
    }
    .tebleDiv {
      width: 100%;
    }
  }
  .input-link /deep/.el-input__inner {
    cursor: pointer;
    color: royalblue;
  }
}
.orderCode {
  line-height: 28px;
  color: #0658CB;
  margin-left: 10px;
  cursor: pointer;
  font-size: 14px;
}
</style>